package gameView;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

/**
 * ImageHandler.java
 * 
 * Fredrik Wallenius and Peter Steiner 
 * DP08 - KTH - 2009
 */
public class ImageHandler{
	
	

	/**
	 * Buffers an image
	 * 
	 * @param String containing picture.type
	 * @return BufferedImage
	 */
	@SuppressWarnings("finally")
	public BufferedImage loadImage(String ref){

		ClassLoader cl = this.getClass().getClassLoader();
		
		BufferedImage img = null;
		try {
			   img = ImageIO.read(new File(ref));
			//img = ImageIO.read(cl.getResource(ref));
			} catch (IOException e) {
			//problemas
				img = null;
				JOptionPane.showMessageDialog(null, "Sorry, could not load resource files...", "Crap coders", JOptionPane.INFORMATION_MESSAGE);
			}finally{
				return img;
			}
	}
	
	/**
	 * Method makes param color invisible
	 * @param String containing picture.type
	 * @return BufferedImage
	 */
	public BufferedImage makeColorTransparent(String ref, Color color) {   
        BufferedImage image = loadImage(ref);   
        BufferedImage dimg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = dimg.createGraphics();   
        g.setComposite(AlphaComposite.Src);   
        g.drawImage(image, null, 0, 0);   
        g.dispose();   
        for(int i = 0; i < dimg.getHeight(); i++) {   
            for(int j = 0; j < dimg.getWidth(); j++) {   
                if(dimg.getRGB(j, i) == color.getRGB()) {   
                dimg.setRGB(j, i, 0x8F1C1C);   
                }   
            }   
        }
        
        return dimg;   
    }  
	
	/**
	 * Mothod Dimmers picture, makes it % invisible
	 * @param img
	 * @param transperancy float value 0-1
	 * @return
	 */
	public BufferedImage loadTranslucentImage(BufferedImage img, float transperancy) {   
        BufferedImage loaded = img;   
        // Create the image using the    
        BufferedImage aimg = new BufferedImage((int)(loaded.getWidth()), (int)(loaded.getHeight()), BufferedImage.TRANSLUCENT);   
        // Get the images graphics   
        Graphics2D g1= aimg.createGraphics();   
        // Set the Graphics composite to Alpha   
        g1.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transperancy));   
        // Draw the LOADED img into the prepared reciver image
        //Valuse given are upper left corner of new image where the old image is to be placed from
        g1.drawImage(loaded, null, 0, 0);   
        // let go of all system resources in this Graphics   
        g1.dispose();   
        // Return the image   
        return aimg;   
    }  

}
